import { clearLoginInfo } from '@/utils'

// 获取请求地址
import { dev, staging, production } from "../baseUrl"
// dev 开发环境；  staging 测试环境；  production  生产环境
const NODE_ENV = 'dev';

let CONFIG;
switch (NODE_ENV){
	case 'production':
		CONFIG = production
		break;
	case 'staging':
		CONFIG = staging
		break;
	default:
		CONFIG = dev
		break;
}

const request = (options) => { 
	return new Promise((resolve, reject) => { 
		uni.request({
			url: `${CONFIG.baseUrl}/${options.url}`,
			method: options.method || "GET",
			header: options.headers || { 
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
				'Content-Type': 'application/json; charset=utf-8'
			},
			data: options.data || {},
			dataType: options.dataType || "json",
			timeout: options.timeout || 20 * 1000,
			success(res) {
				if (res.data.code == 401) {
					clearLoginInfo()
					return
				}else if (res.data.code == 500) {
					uni.showToast({
						icon: 'none',
						title: res.data.msg
					})
					return
				} else {
					resolve(res.data)
				}
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

export {request, CONFIG};